package com.platform.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.platform.annotation.SysLog;
import com.platform.base.BaseService;
import com.platform.common.Const;
import com.platform.common.ServerResponse;
import com.platform.pojo.*;
import com.platform.service.IPsacService;
import com.platform.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * 供应商基本信息服务层
 */
@Service("iPsacService")
public class PsacServiceImpl extends BaseService implements IPsacService {
    /**
     * 根据用户名查询企业基本信息
     * @param userName
     * @return
     */
    @SysLog("根据用户名查询投标人企业基本信息")
    public ServerResponse<Psac0001> selectByUserName(String userName){
        Psac0001 psac0001 = psac0001Mapper.selectByUserName(userName);
        if(null != psac0001){
            return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,psac0001);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);
    }

    /**
     * 根据条件查询投标人部分信息
     * @param paramMap
     * @return
     */
    @SysLog("根据条件查询投标人部分信息")
    public ServerResponse<PageInfo> selectByParamMap(Map paramMap){
        return MapperUtil.pageInfo(paramMap,psac0001Mapper);
    }

    /**
     * 根据ID查询投标人所有基础信息
     * @param id
     * @return
     */
    @SysLog("根据ID查询投标人所有基础信息")
    public ServerResponse<Map> selectById(Integer id){
        //查询出基本信息及开票信息（单个）
        Map resultMap = psac0001Mapper.selectById(id);
        //查询出银行账户信息
        List<Map> resutList =
        psac0002Mapper.selectByUserName(StringUtil.valueOfString(resultMap.get("supplier_code")));
        resultMap.put("bankList",resutList);
        return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,resultMap);
    }

    /**
     * 根据id查询企业基本信息
     * @param id
     * @return
     */
    @SysLog("根据id查询投标人企业基本信息")
    public ServerResponse<Psac0001> selectOneById(Integer id){
        Psac0001 psac0001 = psac0001Mapper.selectByPrimaryKey(id);
        if(null != psac0001){
            return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,psac0001);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);
    }

    /**
     * 新增
     * @param psac0001
     * @return
     */
    @SysLog("新增投标人企业基本信息")
    public ServerResponse<String> insert(Psac0001 psac0001){
        if(psac0001Mapper.insert(psac0001) > 0){
            return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SAVEERROR);
    }

    /**
     * 更新
     * @param psac0001
     * @return
     */
    @SysLog("更新投标人企业基本信息")
    public ServerResponse<String> update(Psac0001 psac0001){
        if(!MapperUtil.selectVersionIsChangeById(psac0001.getId(),psac0001.getVersion(),psac0001Mapper)){
            //判断版本号是否变更
            return ServerResponse.createByErrorMessage(Const.Msg.DATAISUPDATE);
        }
        //更新版本号
        psac0001.setVersion(psac0001.getVersion()+1);
        if(psac0001Mapper.updateByPrimaryKeySelective(psac0001) > 0){
            return ServerResponse.createBySuccessMessage(Const.Msg.UPDATESUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.UPDATEERROR);
    }


    /**
     * 根据用户名查询投标人具体信息
     * @param paramMap
     * @return
     */
    @SysLog("根据用户名查询投标人具体信息")
    public ServerResponse<Map> selectInfoByUserName(Map paramMap,HttpServletRequest request){
        //如果用户名为空，则默认是当前登录用户
        String userName = StringUtil.valueOfString(paramMap.get("userName"));
        if(StringUtil.isEmpty(userName) || "undefined".equals(userName)){
            User u =(User)request.getSession().getAttribute(Const.CURRENT_USER);
            if(null == u){
                return ServerResponse.createByErrorMessage(Const.Msg.USERNOLOGIN);
            }
            userName = u.getUsername();
        }
        //检查权限
        ServerResponse response = PermissionCheckUtil.checkJurisdiction(request,userName);
        if(!response.isSuccess()){
            return response;
        }
        Map resultMap = psac0001Mapper.selectInfoByUserName(userName);
        if(resultMap != null) {
            resultMap.put("company_type1", StringUtil.valueOfString(resultMap.get("company_type1")));
            resultMap.put("three_in_one_flag", StringUtil.valueOfString(resultMap.get("three_in_one_flag")));
            resultMap.put("register_office", StringUtil.valueOfString(resultMap.get("register_office")));
            resultMap.put("taxpayer_type", StringUtil.valueOfString(resultMap.get("taxpayer_type")));
            String establish_date = StringUtil.valueOfString(resultMap.get("establish_date"));//成立日期
            String busi_start_date = StringUtil.valueOfString(resultMap.get("busi_start_date"));//营业期限开始日期
            String busi_end_date = StringUtil.valueOfString(resultMap.get("busi_end_date"));//营业期限结束日期
            //由于数据类型是datetime，需要转成字符串展示，利于后续保存转换
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            try {
                if(StringUtil.isNotEmpty(establish_date)){
                    resultMap.put("establish_date",DateTimeUtil.dateToStr(sdf.parse(establish_date))) ;
                }
                if(StringUtil.isNotEmpty(busi_start_date)){
                    resultMap.put("busi_start_date",DateTimeUtil.dateToStr(sdf.parse(busi_start_date))) ;
                }
                if(StringUtil.isNotEmpty(busi_end_date)){
                    resultMap.put("busi_end_date",DateTimeUtil.dateToStr(sdf.parse(busi_end_date))) ;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //查询附件
            String entityName = StringUtil.valueOfString(paramMap.get("entityName"));
            String entityType = StringUtil.valueOfString(paramMap.get("entityType"));
            String entityType2 = StringUtil.valueOfString(paramMap.get("entityType2"));
            //营业执照
            List<Attachment> fileList = attachmentMapper.selectByParam(entityName,entityType,
                    NumberUtil.safeToNumber(resultMap.get("id")));
            if(null != fileList && 0 < fileList.size()){
                Attachment file = fileList.get(0);
                file.setFiledownpath(PropertiesUtil.getProperty("filehttp")+file.getFiledownpath());
                resultMap.put("file",file);
            }
            //法人委托授权书
            List<Attachment> fileList2 = attachmentMapper.selectByParam(entityName,entityType2,
                    NumberUtil.safeToNumber(resultMap.get("id")));
            if(null != fileList2 && 0 < fileList2.size()){
                Attachment file2 = fileList2.get(0);
                file2.setFiledownpath(PropertiesUtil.getProperty("filehttp")+file2.getFiledownpath());
                resultMap.put("file2",file2);
            }
            return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS, resultMap);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);

    }

    /**
     * 更新投标人状态
     * @param map
     * @param request
     * @return
     */
    @Transactional(rollbackFor = { Exception.class })
    @SysLog("更新投标人状态")
    public ServerResponse<String> examine(Map map, HttpServletRequest request){
        //获取操作人
        Object o = request.getSession().getAttribute(Const.CURRENT_USER);
        User u = null;
        if(null != o){
            u = (User)o;
        }
        if(u == null){
            return ServerResponse.createByErrorMessage(Const.Msg.USERNOLOGIN);
        }
        int pid = NumberUtil.safeToNumber(map.get("id"));
        if(pid == 0){
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        //1.检查版本号是否一致
        int oldVersion = NumberUtil.safeToNumber(map.get("version"));
        if(!MapperUtil.selectVersionIsChangeById(pid,oldVersion,psac0001Mapper)){
            return ServerResponse.createByErrorMessage(Const.Msg.DATAISUPDATE);
        }
        //更新投标人信息状态
        int status = NumberUtil.safeToNumber(map.get("status"));
        if(psac0001Mapper.updateSatusById(pid,status)==0){
            return ServerResponse.createByErrorMessage(Const.Msg.UPDATEERROR);
        }
        //新增审核记录
        Examine examine = new Examine();
        examine.setCatalog("Psaa0001");
        examine.setType("status");
        examine.setValue(pid);
        examine.setOperator(u.getDisplayName());
        examine.setRemark(StringUtil.valueOfString(map.get("rejectRemarks")));
        if(examineMapper.insert(examine) == 0){
            throw new RuntimeException("审核记录添加失败");
        }
        //新增消息通知

        Message message = new Message();
        message.setNoticetype(Const.NoticeType.TIMELY);//即时通知
        message.setUsername(StringUtil.valueOfString(map.get("userName")));//用户名
        message.setMessagestatus(Const.MessageStatus.TAKEEFFECT);//消息状态
        if(status == Const.PsacStatus.TAKEEFFECT){
            //成功
            message.setMessagecontent(Const.MessageContent.PSACTAKEEFFECT);
        }else if(status == Const.PsacStatus.REJECT){
            //驳回
            message.setMessagecontent(Const.MessageContent.PSACREJECT);
        }
        if(messageMapper.insert(message) == 0){
            throw new RuntimeException("消息通知添加失败");
        }
        return ServerResponse.createBySuccessMessage(Const.Msg.UPDATESUCCESS);
    }

    /**
     * 查询用户名银行账户信息
     * @param paramMap
     * @return
     */
    @SysLog("查询用户名银行账户信息")
    public ServerResponse<PageInfo> selectBankAccountByUserName(Map paramMap,HttpServletRequest request){
        String userName = StringUtil.valueOfString(paramMap.get("userName"));
        //如果用户名为空，则默认是当前登录用户
        if(StringUtil.isEmpty(userName) || "undefined".equals(userName)){
            User u =(User)request.getSession().getAttribute(Const.CURRENT_USER);
            if(null == u){
                return ServerResponse.createByErrorMessage(Const.Msg.USERNOLOGIN);
            }
            paramMap.put("userName",u.getUsername());
        }
        //检查权限
        ServerResponse response = PermissionCheckUtil.checkJurisdiction(request,
                StringUtil.valueOfString(paramMap.get("userName")));
        if(!response.isSuccess()){
            return response;
        }
        return MapperUtil.pageInfo(paramMap,psac0002Mapper);
    }


    /**
     * 查询用户名开票信息
     * @param userName
     * @return
     */
    @SysLog("查询用户名开票信息")
    public ServerResponse<Map> selectOpeningInformationByUserName(String userName,HttpServletRequest request){
        //如果用户名为空，则默认是当前登录用户
        if(StringUtil.isEmpty(userName) || "undefined".equals(userName)){
            User u =(User)request.getSession().getAttribute(Const.CURRENT_USER);
            if(null == u){
                return ServerResponse.createByErrorMessage(Const.Msg.USERNOLOGIN);
            }
            userName = u.getUsername();
        }
        //检查权限
        ServerResponse response = PermissionCheckUtil.checkJurisdiction(request,userName);
        if(!response.isSuccess()){
            return response;
        }

        Map resultMap = psac0009Mapper.selectByUserName(userName);
        if(null == resultMap){
            return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);
        }
        return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,resultMap);
    }


    /**
     * Map参数更新投标人信息
     * @param paramMap
     * @param request
     * @return
     */
    @SysLog("更新投标人信息")
    public ServerResponse<String> updateMap(Map paramMap,HttpServletRequest request){
        //查询版本号是否一致
        int oldVersion = NumberUtil.safeToNumber(paramMap.get("version"));
        int id = NumberUtil.safeToNumber(paramMap.get("id"));
        if(id == 0){
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        if(!MapperUtil.selectVersionIsChangeById(id,oldVersion,psac0001Mapper)){
            return ServerResponse.createByErrorMessage(Const.Msg.DATAISUPDATE);
        }
        //判断权限，普通用户只能操作自己的
        ServerResponse response = PermissionCheckUtil.checkJurisdiction(request,
                StringUtil.valueOfString(paramMap.get("supplier_code")));
        if(!response.isSuccess()){
            return response;
        }
        int oldStatus = NumberUtil.safeToNumber(paramMap.get("oldStatus"));
        if(oldStatus == Const.PsacStatus.BEENSAVED){
            return ServerResponse.createByErrorMessage("提交状态不能更改");
        }
        Psac0001 psac0001 = new Psac0001();
        psac0001.setId(id);
        if(oldStatus != Const.PsacStatus.TAKEEFFECT){
            psac0001.setStatus(Const.PsacStatus.BEENSAVED);//状态
        }
        psac0001.setRegisterOffice(NumberUtil.safeToNumber(paramMap.get("register_office")));//注册地
        psac0001.setCompanyName(StringUtil.valueOfString(paramMap.get("company_name")));//企业全称
        psac0001.setChineseName(psac0001.getCompanyName());//中文名称
        psac0001.setCompanyType1(NumberUtil.safeToNumber(paramMap.get("company_type1")));//企业性质
        psac0001.setRegisterAssets(StringUtil.valueOfString(paramMap.get("register_assets")));//注册资本
        psac0001.setThreeInOneFlag(NumberUtil.safeToNumber(paramMap.get("three_in_one_flag")));//是否三证合一
        psac0001.setUscCode(StringUtil.valueOfString(paramMap.get("usc_code")));//统一社会信用代码
        psac0001.setLawer(StringUtil.valueOfString(paramMap.get("lawer")));//法定代表人
        psac0001.setIdcard(StringUtil.valueOfString(paramMap.get("idcard")));//法定代表人身份证号码
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String establishDate = StringUtil.valueOfString(paramMap.get("establish_date"));//成立日期
        try {
            sdf.parse(establishDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(StringUtil.isNotEmpty(establishDate)){
            psac0001.setEstablishDate(DateTimeUtil.strToDate(establishDate));
        }
        String busiStartDate = StringUtil.valueOfString(paramMap.get("busi_start_date"));//营业期限开始日期
        if(StringUtil.isNotEmpty(busiStartDate)){
            psac0001.setBusiStartDate(DateTimeUtil.strToDate(busiStartDate));
        }
        String busiEndDate = StringUtil.valueOfString(paramMap.get("busi_end_date"));//营业期限结束日期
        if(StringUtil.isNotEmpty(busiEndDate)){
            psac0001.setBusiEndDate(DateTimeUtil.strToDate(busiEndDate));
        }
        psac0001.setTaxpayerType(NumberUtil.safeToNumber(paramMap.get("taxpayer_type")));//纳税人类型
        psac0001.setTaxRate(StringUtil.valueOfString(paramMap.get("taxRate")));//税率
        psac0001.setProsecutopmArea(StringUtil.valueOfString(paramMap.get("prosecutopm_area")));//主营业务范围
        psac0001.setAddress(StringUtil.valueOfString(paramMap.get("address")));//公司地址
        psac0001.setTelephone(StringUtil.valueOfString(paramMap.get("telephone")));//公司电话
        psac0001.setAccountLinkman(StringUtil.valueOfString(paramMap.get("account_linkman")));//信息申报联系人
        psac0001.setAccountLinkmanTel(StringUtil.valueOfString(paramMap.get("account_linkman_tel")));//联系人手机
        psac0001.setAccountLinkmanEmail(StringUtil.valueOfString(paramMap.get("account_linkman_email")));//联系人邮箱
        psac0001.setRemarks(StringUtil.valueOfString(paramMap.get("remarks")));//备注
        if(psac0001Mapper.updateByPrimaryKeySelective(psac0001) > 0){
            //更新用户登录信息
            userMapper.updateDisplayNameByUserName(psac0001.getCompanyName(),
                    StringUtil.valueOfString(paramMap.get("supplier_code")));

            return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SAVEERROR);
    }

    /**
     * 新增银行账户信息
     * @param paramMap
     * @return
     */
    @SysLog("新增银行账户信息")
    public ServerResponse<String> saveBankData(Map paramMap,HttpServletRequest request){
        if(paramMap.size() == 0){
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        //将session信息转成map
        String result= StringUtil.valueOfString(paramMap.get("userinfo"));
        Map userMap = JSON.parseObject(result,Map.class);
        String username = StringUtil.valueOfString(userMap.get("username"));
        //判断权限，普通用户只能操作自己的
        ServerResponse response = PermissionCheckUtil.checkJurisdiction(request,username);
        if(!response.isSuccess()){
            return response;
        }
        paramMap.put("username",username);
        Psac0002 psac0002 = new Psac0002();
        psac0002.setBankName(StringUtil.valueOfString(paramMap.get("bank_name")));
        psac0002.setBankAdress(StringUtil.valueOfString(paramMap.get("bank_adress")));
        psac0002.setBankAccount(StringUtil.valueOfString(paramMap.get("bank_account")));
        psac0002.setAccountType(NumberUtil.safeToNumber(paramMap.get("account_type")));
        psac0002.setUsername(StringUtil.valueOfString(paramMap.get("username")));
        if(psac0002Mapper.insert(psac0002) > 0){
            return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SAVEERROR);
    }

    /**
     * 更新银行账户信息
     * @param paramMap
     * @return
     */
    @SysLog("更新银行账户信息")
    public ServerResponse<String> updateBankData(Map paramMap,HttpServletRequest request){
        int id = NumberUtil.safeToNumber(paramMap.get("id"));
        if(id == 0){
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        //将session信息转成map
        String result= StringUtil.valueOfString(paramMap.get("userinfo"));
        Map userMap = JSON.parseObject(result,Map.class);
        String userName = StringUtil.valueOfString(userMap.get("username"));
        //检查权限
        ServerResponse response = PermissionCheckUtil.checkJurisdiction(request,userName);
        if(!response.isSuccess()){
            return response;
        }
        Psac0002 psac0002 = new Psac0002();
        psac0002.setId(id);
        psac0002.setBankName(StringUtil.valueOfString(paramMap.get("bank_name")));
        psac0002.setBankAdress(StringUtil.valueOfString(paramMap.get("bank_adress")));
        psac0002.setBankAccount(StringUtil.valueOfString(paramMap.get("bank_account")));
        psac0002.setAccountType(NumberUtil.safeToNumber(paramMap.get("account_type")));
        if(psac0002Mapper.updateByPrimaryKeySelective(psac0002) > 0){
            return ServerResponse.createBySuccessMessage(Const.Msg.UPDATESUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.UPDATEERROR);
    }

    /**
     * 删除银行账户信息
     * @param id
     * @return
     */
    @SysLog("删除银行账户信息")
    public ServerResponse<String> delBankById(Integer id,HttpServletRequest request){
        Psac0002 psac0002 = psac0002Mapper.selectByPrimaryKey(id);
        if(null == psac0002){
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        //检查权限
        ServerResponse response = PermissionCheckUtil.checkJurisdiction(request,psac0002.getUsername());
        if(!response.isSuccess()){
            return response;
        }
        if(psac0002Mapper.deleteByPrimaryKey(id) > 0){
            return ServerResponse.createBySuccessMessage(Const.Msg.DELSUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.DELSUCCESS);
    }


    /**
     * 保存开票信息
     * @param paramMap
     * @param request
     * @return
     */
    @SysLog("保存开票信息")
    @Transactional(rollbackFor = { Exception.class })
    public ServerResponse<String> saveTicket(Map paramMap,HttpServletRequest request){
        //将session信息转成map
        String result= StringUtil.valueOfString(paramMap.get("userinfo"));
        Map userMap = JSON.parseObject(result,Map.class);
        String userName = StringUtil.valueOfString(userMap.get("username"));
        //检查权限
        ServerResponse response = PermissionCheckUtil.checkJurisdiction(request,userName);
        if(!response.isSuccess()){
            return response;
        }
        int id = NumberUtil.safeToNumber(paramMap.get("id"));
        Psac0009 psac0009 = new Psac0009();
        psac0009.setTaxNumber(StringUtil.valueOfString(paramMap.get("tax_number")));
        psac0009.setCompanyAddress(StringUtil.valueOfString(paramMap.get("company_address")));
        psac0009.setPhone(StringUtil.valueOfString(paramMap.get("phone")));
        psac0009.setBankName(StringUtil.valueOfString(paramMap.get("bank_name")));
        psac0009.setBankAccount(StringUtil.valueOfString(paramMap.get("bank_name")));
        if(id > 0){//更新
            psac0009.setId(id);
            psac0009Mapper.updateByPrimaryKeySelective(psac0009);
        }else{//新增
            psac0009Mapper.insert(psac0009);
        }
        String displayName = StringUtil.valueOfString(paramMap.get("display_name"));
        //更新企业信息名称
        psac0001Mapper.updateNameByUserName(displayName,userName);
        //更新用户登录名称
        userMapper.updateDisplayNameByUserName(displayName,userName);
        return ServerResponse.createBySuccessMessage(Const.Msg.UPDATESUCCESS);
    }
}
